﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using SoftwareConsulting.BI11.Studio.InternalServices;
using SoftwareConsulting.BI11.Studio.Core.Project.Metadata;
using SoftwareConsulting.BI11.Studio.UI.Properties;

namespace SoftwareConsulting.BI11.Studio.UI.ProjectExplorer.ClassificationProblems
{
    public partial class SetClassificationProblemAttributesWeightsDialog : RestorableForm
    {
        private IClassificationProblemWithTraining _problem; //задача классификации с обучением        

        /// <summary>
        /// Инициализирует диалог
        /// </summary>
        private void Initialize()
        {
            var rows = WeightsGrid.Rows;
            rows.Clear();
            var attributes = _problem.AttributesNames;
            if (attributes == null)
            {
                OKButton.Enabled = false;
                return;
            }
            for (int i = 1; i < attributes.GetIndicatorValuesCount(); i++)//с первого, т.к. 0й - [не важно]
            {
                int attributeIndex = i - 1;
                rows.Add();
                var row = rows[attributeIndex];
                var cells = row.Cells;
                (cells[0] as DataGridViewTextBoxCell).Value = attributes.GetIndicatorValueByPosition(i).Value as string;
                (cells[1] as DataGridViewTextBoxCell).Value = Convert.ToInt32(Math.Round(_problem.GetAttributeInfo(attributeIndex))).ToString(CultureInfo.CurrentUICulture);
            }
        }

        /// <summary>
        /// Применяет изменения и закрывает диалог
        /// </summary>
        private void ApplyAndClose()
        {            
            var rows = WeightsGrid.Rows;
            var attributes = _problem.AttributesNames;
            int[] weights = new int[rows.Count];
            for (int i = 0; i < rows.Count; i++)
            {
                var row = rows[i];
                var cells = row.Cells;
                string valStr = (cells[1] as DataGridViewTextBoxCell).Value as string;
                int val = 0;
                bool parsed = int.TryParse(valStr, NumberStyles.Integer, CultureInfo.CurrentUICulture, out val);
                parsed = parsed && (val >= 0);
                if (!parsed)
                {
                    GeneralMethods.ShowUserError(Resources.BI_PROJECTEXPLORER_CLASSIFICATIONPROBLEM_WITHTRAINING_SETATTRIBUTESINFO_WEIGHTS_INCORRECTNUMBER);
                    cells[1].Selected = true;
                    WeightsGrid.CurrentCell = cells[1];
                    WeightsGrid.BeginEdit(true);
                    DialogResult = DialogResult.None;
                    return;
                }
                weights[i] = val;
            }
            ///нельзя задавать сразу в первом цикле, 
            ///т.к. если были ошибки ввода, то предыдущие 
            ///правильно введенные строки не должны применяться
            for (int i = 0; i < rows.Count; i++)
            {
                _problem.SetAttributeInfo(i, weights[i]);
            }
            DialogResult = DialogResult.OK;
            Close();
        }

        /// <summary>
        /// Отменяет изменения и закрывает диалог
        /// </summary>
        private void CancelAndClose()
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        public SetClassificationProblemAttributesWeightsDialog(IClassificationProblemWithTraining problem)
        {
            _problem = problem;
            InitializeComponent();
        }

        private void OKButton_Click(object sender, EventArgs e)
        {
            ApplyAndClose();
        }

        private void CancelWeightsButton_Click(object sender, EventArgs e)
        {
            CancelAndClose();
        }

        private void SetClassificationProblemAttributesWeightsDialog_Load(object sender, EventArgs e)
        {
            Initialize();
        }
    }
}
